﻿using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;

namespace Utils
{
    /// <summary>
    /// 网络工具
    /// </summary>
    public class NetworkUtil
    {
        /// <summary>
        /// 获取所有网卡信息
        /// </summary>
        public static List<Interface> ListNetworkInterface()
        {
            List<Interface> interfaces = new List<Interface>();
            var nics = NetworkInterface.GetAllNetworkInterfaces();
            foreach(var nic in nics)
            {
                //封装成自己的Interface
                Interface inter = new Interface();
                inter.Id = nic.Id;
                inter.Name = nic.Name;
                inter.Description = nic.Description;
                inter.Up = nic.OperationalStatus == OperationalStatus.Up;
                inter.Wlan = nic.NetworkInterfaceType == NetworkInterfaceType.Wireless80211;
                var ipProperties = nic.GetIPProperties();
                var unAddrs = ipProperties.UnicastAddresses;
                // DNS
                if(ipProperties.DnsAddresses.Count > 0)
                {
                    inter.DNS1 = ipProperties.DnsAddresses[0].ToString();
                }
                if (ipProperties.DnsAddresses.Count > 1)
                {
                    inter.DNS2 = ipProperties.DnsAddresses[1].ToString();
                }
                if (ipProperties.GatewayAddresses.Count > 0)
                    inter.DefaultGateway = ipProperties.GatewayAddresses[0].Address.ToString();
                // GATEWAY
                foreach (var unaddr in unAddrs)
                {
                    if(unaddr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        inter.IpAddress = unaddr.Address.ToString();
                        inter.NetMask = unaddr.IPv4Mask.ToString();
                        if(unaddr.PrefixOrigin == PrefixOrigin.Dhcp)
                        {
                            inter.InterfaceConfigIpMethod = InterfaceConfigIpMethod.DHCP;
                        }
                        else
                        {
                            inter.InterfaceConfigIpMethod = InterfaceConfigIpMethod.STATIC;
                        }
                    }
                    if(unaddr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                    {

                    }
                }
                interfaces.Add(inter);
            }
            return interfaces;
        }
        /// <summary>
        /// 获取接口
        /// </summary>
        /// <param name="interface"></param>
        public static Interface GetWorkInterface(string @interface)
        {
            return ListNetworkInterface().Where(inter => inter.Name.Contains(@interface)).FirstOrDefault();
        }
    }
}
